<template>
  <div class="ticket_admin">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane style="margin-top: 30px;" label="航班列表" name="first">
        <el-row style="text-align: left; margin-top: -10px; margin-bottom: 20px;" :gutter="20">
          <el-col :span="12">
            <el-button type="primary" size="mini" @click="updateTicketExcel"><i class="el-icon-document-add"></i> 上传机票
            </el-button>
            <el-button type="primary" size="mini" @click="refreshViews"> <i class="el-icon-refresh"></i> 刷新
            </el-button>
          </el-col>
        </el-row>
        <div id="baseTicketDataContainer"></div>
        <el-card style="margin-top: 30px;" shadow="always">
          <el-table :data="ticketTableDataPage" height="450" border style="width: 100%"
            :default-sort="{prop: 'startDate', order: 'descending'}">
            <el-table-column fixed prop="flightNumber" label="航班号" width="200">
            </el-table-column>
            <el-table-column prop="startCity" label="起飞城市" width="180">
            </el-table-column>
            <el-table-column prop="arriveCity" label="抵达城市" width="180">
            </el-table-column>
            <el-table-column prop="startDate" sortable label="起飞时间" width="180">
            </el-table-column>
            <el-table-column prop="arriveDate" sortable label="抵达时间" width="180">
            </el-table-column>
            <el-table-column prop="gds" label="航空公司" width="180">
            </el-table-column>
            <el-table-column prop="createTime" sortable label="创建时间" width="180">
            </el-table-column>
            <el-table-column prop="updateTime" sortable label="更新时间" width="180">
            </el-table-column>
            <el-table-column label="操作" width="100">
              <template slot-scope="scope">
                <el-button type="primary" size="mini" @click="ticketDetails(scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="margin-top: 20px; text-align: right;" background layout="sizes,prev, pager, next"
            :total="ticketTableData.length" @size-change="pageSizeChange" :hide-on-single-page="true"
            @prev-click="pagePrevClick" @next-click="pageNextClick" @current-change="pageCurrentChange">
          </el-pagination>
        </el-card>
        <div id="container"></div>
      </el-tab-pane>
      <el-tab-pane style="text-align: left;" label="机票详情" name="second">
        航班号查询
        <el-select @change="changeOptions" v-model="value" clearable placeholder="请选择">
          <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value">
          </el-option>
        </el-select>
        <el-card style="margin-top: 30px;" shadow="always">
          <el-table :data="ticketTableDataPage" height="450" border style="width: 100%"
            :default-sort="{prop: 'startDate', order: 'descending'}">
            <el-table-column fixed prop="flightNumber" label="航班号" width="200">
            </el-table-column>
            <el-table-column prop="startCity" label="起飞城市" width="180">
            </el-table-column>
            <el-table-column prop="arriveCity" label="抵达城市" width="180">
            </el-table-column>
            <el-table-column prop="startDate" sortable label="起飞时间" width="180">
            </el-table-column>
            <el-table-column prop="arriveDate" sortable label="抵达时间" width="180">
            </el-table-column>
            <el-table-column prop="gds" label="航空公司" width="180">
            </el-table-column>
            <el-table-column prop="createTime" sortable label="创建时间" width="180">
            </el-table-column>
            <el-table-column prop="updateTime" sortable label="更新时间" width="180">
            </el-table-column>
            <el-table-column prop="price" sortable label="机票价格" width="180">
            </el-table-column>
            <el-table-column prop="ticketLevel" label="机票舱等" width="180">
              <template slot-scope="scope">
                <span v-if="scope.row.ticketLevel == 0">商务舱</span>
                <span v-if="scope.row.ticketLevel == 1">一等舱</span>
                <span v-if="scope.row.ticketLevel == 2">二等舱</span>
                <span v-if="scope.row.ticketLevel == 3">三等舱</span>
                <span v-if="scope.row.ticketLevel == 4">四等舱</span>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="是否售出" width="180">
              <template slot-scope="scope">
                <span v-if="scope.row.status == 0">已经售出</span>
                <span v-if="scope.row.status == 1">未售出</span>
              </template>
            </el-table-column>
            <el-table-column prop="seatNumber" label="座位类型" width="180">
            </el-table-column>
            <el-table-column prop="aircraftNumber" label="客机类型" width="180">
              <template slot-scope="scope">
                <span v-if="scope.row.aircraftNumber == 0">大型客机</span>
                <span v-if="scope.row.aircraftNumber == 1">中型客机</span>
                <span v-if="scope.row.aircraftNumber == 2">小型客机</span>
              </template>
            </el-table-column>
          </el-table>
          <el-pagination style="margin-top: 20px; text-align: right;" background layout="sizes,prev, pager, next"
            :total="tiketTableDataDetails.length" @size-change="sizeChange" :hide-on-single-page="true"
            @prev-click="prevClick" @next-click="nextClick" @current-change="currentChange">
          </el-pagination>
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <el-dialog title="上传机票表格(excel)" :visible.sync="ticketUpdate">
      <template>
        <div>
          <el-upload drag :limit=limitNum :auto-upload="true" accept=".xlsx"
            action="http://localhost:8090/operation-analysis-service/operationAnalysis/uploadTicketExcel" multiple
            :before-upload="beforeUploadFile" :on-change="fileChange" :on-exceed="exceedFile"
            :on-success="handleSuccess" :on-error="handleError" :file-list="fileList">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">只能上传xlsx文件，且不超过10M</div>
          </el-upload>
          <br />
          <el-button size="small" @click="cancelUpdate">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
  import DataSet from '@antv/data-set';
  import {
    Chart
  } from '@antv/g2';
  import ticket from "@/api/ticket/ticket";
  import axios from 'axios'
  export default {
    filters: {

    },
    data() {
      return {
        limitNum: 1, // 上传excell时，同时允许上传的最大数
        fileList: [], // excel文件列表
        ticketUpdate: false,
        activeName: "first",
        ticketTableData: [],
        baseTicketData: [],
        baseTicketDataContainerChart: '',
        isFirstLoad: true,
        ticketDetailData: [],
        ticketTableDataPage: [],
        ticketDetailsChart: '',
        options: [],
        value: '',
        tiketTableDataDetails: [],
        pageSize: 10,
        flightPageSize: 10
      }
    },
    created() {

    },
    mounted() {
      let vm = this
      vm.queryTicketList()
      vm.initFlightNumberList()
      vm.initBaseTicketData()
    },
    methods: {
      // 前端分页
      prevClick(e) {
        this.ticketTableDataPage = this.tiketTableDataDetails.slice((e - 1) * this.pageSize, e * this
          .pageSize)
      },
      nextClick(e) {
        this.ticketTableDataPage = this.tiketTableDataDetails.slice((e - 1) * this.pageSize, e * this
          .pageSize)
      },
      currentChange(e) {
        this.ticketTableDataPage = this.tiketTableDataDetails.slice((e - 1) * this.pageSize, e * this
          .pageSize)
      },
      sizeChange(e) {
        this.pageSize = e
        this.ticketTableDataPage = this.tiketTableDataDetails.slice(0, this
          .pageSize)
      },


      pagePrevClick(e) {
        this.ticketTableDataPage = this.ticketTableData.slice((e - 1) * this.flightPageSize, e * this
          .flightPageSize)
      },
      pageNextClick(e) {
        this.ticketTableDataPage = this.ticketTableData.slice((e - 1) * this.flightPageSize, e * this
          .flightPageSize)
      },
      pageCurrentChange(e) {
        this.ticketTableDataPage = this.ticketTableData.slice((e - 1) * this.flightPageSize, e * this
          .flightPageSize)
      },
      pageSizeChange(e) {
        this.flightPageSize = e
        this.ticketTableDataPage = this.ticketTableData.slice(0, this.flightPageSize)
      },
      changeOptions(value) {
        let vm = this
        if (value.trim() == '') {
          vm.$message.warning('查询条件不能为空')
          return
        }
        axios({
          url: process.env.BASE_API + `/operation-analysis-service/operationAnalysis/queryAllByFlightNumber/` +
            value,
          method: 'get'
        }).then(function(res) {
          if (res.data.success) {
            vm.tiketTableDataDetails = res.data.data.tickets
            vm.ticketTableDataPage = vm.tiketTableDataDetails.slice(0, vm
              .pageSize)
            vm.$message.success(res.data.message)
          } else {
            vm.$message.warning(res.data.message)
          }
        })
      },
      initFlightNumberList() {
        //  加载视图
        let vm = this
        axios({
          url: process.env.BASE_API + `/operation-analysis-service/operationAnalysis/queryFlightNumberList`,
          method: 'get'
        }).then(function(res) {
          if (res.data) {
            vm.options = res.data.data.flightNumberOptions
            vm.$message.success(res.data.message)
          } else {
            vm.$message.warning(res.data.message)
          }
        });
      },
      async queryTicketList() {
        let vm = this
        vm.ticketTableData = []
        await axios({
          url: process.env.BASE_API + `/operation-analysis-service/operationAnalysis/queryTicketList`,
          method: 'get'
        }).then(function(res) {
          vm.ticketTableData = res.data.data.tickets
          vm.ticketTableDataPage = vm.ticketTableData.slice(0, vm.flightPageSize)
          vm.$message.success(res.data.message)
        });
      },
      submitUpload() {
        this.$refs.upload.submit();
      },
      // 文件超出个数限制时的钩子
      exceedFile(files, fileList) {
        this.$message.warning(`只能选择 ${this.limitNum} 个文件，当前共选择了 ${files.length + fileList.length} 个`);
      },
      // 文件状态改变时的钩子
      fileChange(file, fileList) {
        console.log('ddd upload');
        // this.fileList.push(file.raw);
        console.log(this.fileList);
      },
      // 上传文件之前的钩子, 参数为上传的文件,若返回 false 或者返回 Promise 且被 reject，则停止上传
      beforeUploadFile(file) {
        console.log('before upload');
        console.log(file);
        let extension = file.name.substring(file.name.lastIndexOf('.') + 1);
        let size = file.size / 1024 / 1024;
        if (extension !== 'xlsx') {
          this.$message.warning('只能上传后缀是.xlsx的文件');
        }
        if (size > 10) {
          this.$message.warning('文件大小不得超过10M');
        }
      },
      // 文件上传成功时的钩子
      handleSuccess(res, file, fileList) {
        let vm = this
        vm.$message.success('文件上传成功，后台正在解析文件中，请单击刷新即可');
        vm.ticketUpdate = false;
        vm.fileList = [];
        vm.queryTicketList()
      },
      // 文件上传失败时的钩子
      handleError(err, file, fileList) {
        console.log('ccc upload');
        this.$message.error('文件上传失败');
        this.ticketUpdate = false;
        this.fileList = [];
      },
      // 点击取消的文件上传
      cancelUpdate() {
        let vm = this
        vm.$message({
          message: '取消上传',
          type: 'warning'
        });

        vm.ticketUpdate = false;
        vm.fileList = [];
      },
      handleClick() {
        console.log("切换 tab")
      },
      refreshViews() {
        let vm = this
        vm.baseTicketDataContainerChart.destroy();
        vm.initBaseTicketData()
        vm.initFlightNumberList()
        vm.queryTicketList()
      },
      // 上传机票
      updateTicketExcel() {
        let vm = this
        vm.ticketUpdate = true;
      },
      // 加载基本视图
      initBaseTicketData() {
        let vm = this
        axios({
          url: process.env.BASE_API + `/operation-analysis-service/operationAnalysis/queryBaseTicketData`,
          method: 'get'
        }).then(function(res) {
          vm.baseTicketData = res.data.data.baseTicketData
          if (!res.data.success) {
            this.$message.warning(res.data.message);
            return
          }
          vm.baseTicketDataContainerChart = new Chart({
            container: 'baseTicketDataContainer',
            autoFit: true,
            height: 500,
          });
          vm.baseTicketDataContainerChart.data(vm.baseTicketData);
          vm.baseTicketDataContainerChart.scale('count', {
            nice: true,
          });
          vm.baseTicketDataContainerChart.tooltip({
            showMarkers: false,
            shared: true,
          });

          vm.baseTicketDataContainerChart
            .interval()
            .position('flightNumber*count')
            .color('isSellOut')
            .adjust([{
              type: 'dodge',
              marginRatio: 0,
            }, ]);

          vm.baseTicketDataContainerChart.interaction('element-highlight-by-x');

          vm.baseTicketDataContainerChart.render();
        });
      },
      ticketDetails(row) {
        let vm = this
        axios({
          url: process.env.BASE_API + `/operation-analysis-service/operationAnalysis/queryTicketDetailData/` + row
            .flightNumber,
          method: 'get'
        }).then(function(res) {
          vm.ticketDetailData = res.data.data.ticketDetailData
          if (!res.data.success) {
            this.$message.warning(res.data.message);
            return
          }
          if (!vm.isFirstLoad) {
            vm.ticketDetailsChart.destroy()
          }
          vm.isFirstLoad = false
          const ds = new DataSet();
          const dv = ds.createView();
          dv.source(vm.ticketDetailData).transform({
            type: 'percent',
            field: 'value',
            dimension: 'type',
            as: 'percent',
          });

          const colorMap = {
            商务座: '#1890ff',
            一等座: '#2f5fc9',
            二等座: '#971aff',
            三等座: '#00ff4a',
            四等座: '#ff8b00',
          };

          vm.ticketDetailsChart = new Chart({
            container: 'container',
            autoFit: true,
            height: 600,
          });
          vm.ticketDetailsChart.data(dv.rows);
          vm.ticketDetailsChart.legend(false);
          vm.ticketDetailsChart.coordinate('theta', {
            radius: 0.5,
            innerRadius: 0.3,
          });
          vm.ticketDetailsChart.tooltip({
            showMarkers: false
          });
          vm.ticketDetailsChart
            .interval()
            .adjust('stack')
            .position('percent')
            .color('type', (val) => colorMap[val])
            .style({
              stroke: 'white',
              lineWidth: 1,
            })
            .label('type', {
              offset: -5,
              style: {
                fill: 'white',
                shadowBlur: 2,
                shadowColor: 'rgba(223, 223, 223, 0.5)',
              },
            });

          const ds2 = new DataSet();
          const dv2 = ds2.createView();
          dv2.source(vm.ticketDetailData).transform({
            type: 'percent',
            field: 'value',
            dimension: 'name',
            as: 'percent',
          });
          const outterView = vm.ticketDetailsChart.createView();
          outterView.data(dv2.rows);
          outterView.coordinate('theta', {
            innerRadius: 0.5 / 0.8,
            radius: 0.8,
          });
          outterView
            .interval()
            .adjust('stack')
            .position('percent')
            .color('type*name', (type, name) => colorMap[type])
            .style({
              stroke: 'white',
              lineWidth: 1,
            })
            .label('name', {
              offset: -10,
              style: {
                fill: 'white',
                shadowBlur: 2,
                shadowColor: 'rgba(212, 212, 212, 0.5)',
              },
            });
          vm.ticketDetailsChart.interaction('element-active')
          vm.ticketDetailsChart.render();

          vm.$message.success("视图已经渲染到下方～");
        })
      }
    }
  }
</script>
<style>
  .ticket_admin {
    text-align: center;
    margin-left: 2%;
    margin-right: 2%;
  }

  .el-tabs--left .el-tabs__nav-wrap.is-left::after {
    width: 0px;
  }

  .el-tabs__nav-wrap::after {
    height: 0px;
  }
</style>
